package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import com.sun.xml.internal.ws.api.message.AddressingUtils;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@Service
@Slf4j
public class AuditServiceImpl implements AuditService {
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Override
    public void insertAudit(Application application) {
        //System.out.println(1/0); //演示错误
        log.debug("新增审批表单：{}",application);
        //获取到审批人的id的集合
        List<Long> auditUserIdList = application.getAuditUserIdList();
        //遍历该集合，获取对应的信息
        for (int i = 0; i < auditUserIdList.size(); i++) {
            //初始化一个审批对象
            Audit audit = new Audit();
            //为当前审批对象设置对应的申请表单id
            audit.setApplicationId(application.getId());
            //为当前审批对象设置审批人的id
            audit.setAuditUserId(auditUserIdList.get(i));
            //i==0时，表示是第一个审批单，这个审批单的状态需要设置为“待我审核”
            if(i==0) {
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            //审批排序
            audit.setAuditSort(i);
            //调用mapper中的新增方法
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
        //遍历auditVOS
        for (int i = 0; i < auditVOS.size(); i++) {
            AuditVO auditVO = auditVOS.get(i);
            //将对applicationVO对象的操作进行封装
            assignAuditUserList(auditVO);
        }
        //记得返回
        return auditVOS;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        //初始化Audit对象
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        //准备一个申请表对象
        Application application = new Application();
        //赋值id
        application.setId(auditSaveParam.getApplicationId());
        //审核
        //审核通过--状态30  已审核
        //驳回 -- 直接去修改工单的状态---状态40
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){
            //更新到数据库中，当前审批单对象的状态为已审核
            auditMapper.update(audit);
            //继续查询其他审批单
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(auditSaveParam.getApplicationId());
            Integer counts = auditMapper.selectRestAuditCount(auditQuery);
            if(counts>0){
                //表示还有未审核的数据
                //下一条要审批数据的sort+1
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                //查询下一条要审核的数据
                List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
                //判断auditVOS集合是否null
                if(auditVOS!=null && auditVOS.size()>0){
                    AuditVO auditVO = auditVOS.get(0);
                    Audit audit1 = new Audit();
                    audit1.setId(auditVO.getId());
                    audit1.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    auditMapper.update(audit1);
                }
                //申请表数据要修改状态  审核中
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else{
                //设置车辆申请单的状态为已审核
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        } else if(audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())){
            //更新审批单为驳回
            auditMapper.update(audit);
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //根据申请表单的id查询所有审核单
            List<AuditVO> auditVOS = auditMapper.selectAudit(auditQuery);
            //判断非空
            if(auditVOS!=null && auditVOS.size()>0){
                //遍历审核集合
                for (int i = 0; i < auditVOS.size(); i++) {
                    AuditVO auditVO = auditVOS.get(i);
                    //如果审核单还处于“待我审核”，删除
                    if(AuditStatusEnum.MY_PENDING.getCode().equals(auditVO.getAuditStatus())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            //application对象的状态设置为40
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            //设置驳回原因
            application.setRejectReason(auditSaveParam.getRejectReason());
            //更新申请表单状态
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        //查询审批人的信息
        List<AuditVO> auditVOS = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //审批人的id集合，审批人姓名的集合
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //遍历auditVOS对象
        for (int i = 0; i < auditVOS.size(); i++) {
            //获取审批人userId
            Long userId = auditVOS.get(i).getAuditUserId();
            //将userId赋值到auditUserIdList集合中
            auditUserIdList.add(userId);
            //查询用户信息UserMapper
            UserVO userVO = userMapper.selectById(userId);
            //用户不存在
            if(userVO==null)
                //跳出本次循环，进入下一次循环
                continue;
            //将userVo中username存入到auditUsernameList集合中
            auditUsernameList.add(userVO.getUsername());
        }
        //将准备好的审批人的id集合数据赋值给applicationVO
        auditVO.setAuditUserIdList(auditUserIdList);
        //需要一个工具，进行值与值之间的拼接
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList) {
            stringJoiner.add(username);
        }
        //将拼接好的username的列表转成一个字符串，将string赋值到applicationVO对象中
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
